package com.xiaomi.shwx.controller.user;


import com.alibaba.fastjson.JSON;
import com.xiaomi.shwx.common.exception.BaseException;
import com.xiaomi.shwx.common.result.Result;
import com.xiaomi.shwx.common.result.ResultCodeEnum;
import com.xiaomi.shwx.common.util.Constant;
import com.xiaomi.shwx.common.util.JwtUtil;
import com.xiaomi.shwx.common.util.RedisConst;
import com.xiaomi.shwx.entity.dto.UserLoginDTO;
import com.xiaomi.shwx.entity.dto.UserRegDTO;
import com.xiaomi.shwx.entity.pojo.User;
import com.xiaomi.shwx.entity.vo.UserLoginVO;
import com.xiaomi.shwx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lei
 * @since 2024-05-13
 */
@RestController
@Slf4j
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 登录
     * @param dto
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO dto) {
        log.info("登录:{}", dto);
        if (Objects.isNull(dto)) {
            throw new BaseException(ResultCodeEnum.PARAMS_ERROR);
        }
        // 认证
        UserLoginVO login = userService.login(dto);
        if (Objects.isNull(login)){
            return Result.fail().message(Constant.USER_PASSWORD_ERROR);
        }else {
            // 使用jwt生成token
            String token = JwtUtil.createToken(login.getId());
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token, JSON.toJSONString(login), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            //返回页面信息
            HashMap<String, Object> map = new HashMap<>();
            map.put("user",login);
            map.put("token", token);
            return Result.ok(map);
        }
    }

    /**
     * 注册
     * @param dto
     * @return
     */
    @PostMapping("/register")
    public Result<UserLoginVO> register(@RequestBody UserRegDTO dto) {
        log.info("注册:{}", dto);
        if (Objects.isNull(dto)) {
            throw new BaseException(ResultCodeEnum.PARAMS_ERROR);
        }
        return Result.ok(userService.register(dto));
    }

}
